﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Douban.Core
{
    public class Digest
    {
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.RegisterAttached("Text", typeof(string), typeof(Digest), new UIPropertyMetadata(PropertyChangedCallback));

        public static readonly DependencyProperty OriginTextProperty =
            DependencyProperty.RegisterAttached("OriginText", typeof(string), typeof(Digest), new UIPropertyMetadata(null));

        public static readonly DependencyProperty SignatureChangedProperty =
            DependencyProperty.RegisterAttached("SignatureChanged", typeof(bool), typeof(Digest), new UIPropertyMetadata(null));

        public static string GetText(TextBlock obj)
        {
            return (string)obj.GetValue(TextProperty);
        }

        public static void SetText(TextBlock obj, string value)
        {
            obj.SetValue(TextProperty, value);
        }

        public static string GetOriginText(DependencyObject obj)
        {
            return (string)obj.GetValue(OriginTextProperty);
        }

        public static void SetOriginText(DependencyObject obj, string value)
        {
            obj.SetValue(OriginTextProperty, value);
        }

        public static bool GetSignatureChanged(DependencyObject obj)
        {
            return (bool)obj.GetValue(SignatureChangedProperty);
        }

        public static void SetSignatureChanged(DependencyObject obj, bool value)
        {
            obj.SetValue(SignatureChangedProperty, value);
        }      

        private static void PropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            SetOriginText(sender, e.NewValue.ToString());
            TextBlock block = (TextBlock)sender;
            block.Text = e.NewValue.ToString();
            block.SizeChanged += new SizeChangedEventHandler(block_SizeChanged);
        }

        private static void block_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            TextBlock block = (TextBlock)sender;

            if (GetSignatureChanged(block))
            {
                SetSignatureChanged(block, false);
                return;
            }
            SetSignatureChanged(block, true);
           
            string originText = GetOriginText(block);
            int displayLength = (int)(block.ActualWidth / block.FontSize);

            if (displayLength < originText.Length - 1)
            {
                string displaySignature = originText.Substring(0, displayLength);
                block.Text = displaySignature + "...";
            }
            else
                block.Text = originText;
        }
    }
}
